layui.use(['form','layer','table','laytpl','laypage','element'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table,
        element = layui.element;

    var currTabType;
    //用户列表
    var tableIns = table.render({
        elem: '#userList',
        url : '/userList',
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limits : [10,15,20,25],
        limit : 10,
        id : "userListTable",
        // toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        // defaultToolbar: ['exports', 'print'],
        cols : [[
        {type: "checkbox", fixed:"left", width:50},
        {type: "numbers",title: '序号', width:50},
        {field: 'id', title: 'ID',width:0, minWidth:0,hide:true},
        {field: 'username', title: '用户名', width:100, align:"center"},
        {field: 'name', title: '姓名', width:80, align:'center'},
        {field: 'sex', title: '性别', width:60, align:'center'},
        {field: 'sfz', title: '身份证', minWidth:70, align:'center'},
        {field: 'email', title: '邮箱', minWidth:80, align:'center',templet:function(d){
                return '<a class="layui-blue" href="mailto:'+d.email+'">'+d.email+'</a>';
            }},
        /*{field: 'email', title: '邮箱', Width:80, align:"center"},*/
        {field: 'mobile', title: '手机号码', minWidth:80, align:"center"},
        {field: 'roles', title: '角色', minWidth:50, align:'center'},
        {field: 'status', title: '状态', width:60, align:'center',templet:function(d){
                return d.status == 0 ? "禁用" : "启用";
            }},
        {field: 'lastTime', title: '最后登录时间', align:'center',minWidth:100,templet:function (d) {
                return (d.lastTime==null) ?"无":d.lastTime;
            }},
        {title: '操作', minWidth:270,fixed:"right",align:"center",templet:"#userListBar"}
        ]],
        done: function () {
            // $("[data-field='id']").css('display','none');
        }
    });

    //一些事件监听
    element.on('tab(userListTabBrief)', function(data){
        currTabType = $(this).attr('data-type');
        refresh();
    });
    function refresh(){
        table.reload("userListTable",{
            url:"/userList",
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                name: $(".searchVal").val()  //搜索的关键字
                ,range: currTabType
                ,xxxxId: $("#xxxxId").val()
            }
        })
    }
    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click",function(){
        refresh();
        // if($(".searchVal").val() != ''){
        // }else{
        //     layer.msg("请输入搜索的内容");
        // }
    });

    //添加用户
    function addUser(edit){
        var index;
        if (edit) {
        index = layui.layer.open({
            title : "编辑用户",
            type : 2,
            content : "/toUserModify?id="+edit.id,
            success : function(data){
                setTimeout(function(){
                    layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        });
        }else{
            index = layui.layer.open({
                title : "添加用户",
                type : 2,
                content : "/toUserAdd",
                success : function(layero, index){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500)
                }
            });
        }
        layui.layer.full(index);
        window.sessionStorage.setItem("index",index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }
    $(".addNews_btn").click(function(){
        addUser();
    });

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('schoolListTable'),
            data = checkStatus.data,
            id = "";
        if(data.length > 0) {
            for (var i in data) {
                if(i==data.length-1){
                    id+=data[i].id;
                }else{
                    id+=data[i].id+",";
                }
            }
            layer.confirm('确定删除选中的用户？', {icon: 3, title: '提示信息'}, function (index) {
                $.get("/userDel",{
                    id : id //将需要删除的newsId作为参数传入
                },function(data){
                    if (data =="success") {
                        tableIns.reload();
                        layer.close(index);
                    }else if (data == "error") {
                        layer.msg("用户删除失败！");
                    }else if (data == "logout") {
                        layer.close(index);
                        var curWwwPath = window.document.location.href;
                        var pathName = window.document.location.pathname;
                        var pos = curWwwPath.indexOf(pathName);
                        var localhostPaht = curWwwPath.substring(0, pos);
                        parent.location.href = localhostPaht+"/logout";
                    }
                })
            })
        }else{
            layer.msg("请选择需要删除的用户");
        }
    });
    //批量重置密码
    $(".reset_btn").click(function(){
        var checkStatus = table.checkStatus('schoolListTable'),
            data = checkStatus.data,
            id = "";
        if(data.length > 0) {
            for (var i in data) {
                if(i==data.length-1){
                    id+=data[i].id;
                }else{
                    id+=data[i].id+",";
                }
            }
            layer.confirm('确定重置选中用户的密码？', {icon: 3, title: '提示信息'}, function (index) {
                $.get("/resetPwd",{
                    id : id //将需要删除的newsId作为参数传入
                },function(data){
                    if (data =="success") {
                        tableIns.reload();
                        layer.close(index);
                    }else if (data == "error") {
                        layer.msg("重置密码失败！");
                    }
                })
            })
        }else{
            layer.msg("请选择需要重置的用户");
        }
    });

    //列表操作
    table.on('tool(userList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){ //编辑
            addUser(data);
        }else if(layEvent === 'usable'){ //启用禁用
            if (data.status==1) {
                usableText = "是否确定禁用此用户？",
                    btnText = "已禁用";
            }else{
                usableText = "是否确定启用此用户？",
                    btnText = "已启用";
            }
            layer.confirm(usableText,{
                icon: 3,
                title:'系统提示',
                cancel : function(index){
                    layer.close(index);
                }
            },function(index){
                $.post("/changeStatus",{
                    id:data.id,
                    status:data.status
                },function(data){
                    if (data=="success") {
                        layer.close(index);
                        layer.msg(btnText);
                        tableIns.reload();
                    }else{
                        layer.close(index);
                        layer.msg("状态修改失败！");
                        tableIns.reload();
                    }
                });
            },function(index){
                layer.close(index);
            });
        }else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除此用户？',{icon:3, title:'提示信息'},function(index){
                $.get("/userDel",{
                    id : data.id //参数传入
                },function(data){
                    if (data =="success") {
                        tableIns.reload();
                        layer.close(index);
                    }else if (data == "error") {
                        layer.msg("用户删除失败！");
                    }else if (data == "logout") {
                        layer.close(index);
                        var curWwwPath = window.document.location.href;
                        var pathName = window.document.location.pathname;
                        var pos = curWwwPath.indexOf(pathName);
                        var localhostPaht = curWwwPath.substring(0, pos);
                        parent.location.href = localhostPaht+"/logout";
                    }

                })
            });
        }else if (layEvent === 'reset') {
            layer.confirm('确定重置此用户密码？',{icon:3, title:'提示信息'},function(index){
                $.get("/resetPwd",{
                    id : data.id //参数传入
                },function(data){
                    if (data =="success") {
                        tableIns.reload();
                        layer.close(index);
                    }else if (data == "error") {
                        layer.msg("重置密码失败！");
                    }

                })
            });
        }
    });
/*    document.onkeydown = function(e){
        var ev = document.all ? window.event : e;
        if(ev.keyCode==13) {
            table.reload("userListTable",{
                url:"/userList",
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    name: $(".searchVal").val()  //搜索的关键字
                }
            })
        }
    }*/
})
